package com.eportal.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.apache.log4j.Logger;

/**
 * Created by smzhang on 2015/12/29.
 */
public class ValidateUtil {
	
	private static Logger log = Logger.getLogger(ValidateUtil.class);


    public static <T> String validate(T t) {
        try {
            StringBuffer buf = new StringBuffer();
            ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
            Validator validator = factory.getValidator();
            Set<ConstraintViolation<T>> constraintViolations = validator.validate(t);
            for (Iterator<ConstraintViolation<T>> iter = constraintViolations.iterator(); iter.hasNext(); ) {
                ConstraintViolation violation = iter.next();
                buf.append(violation.getMessage() + "<BR>");
            }
            return buf.toString();
        } catch (Exception e) {
        	log.error("error",e);
        }
        return null;
    }

    public static <T> String validate(T t, String... fields) {
        try {
            StringBuffer buf = new StringBuffer();
            ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
            Validator validator = factory.getValidator();
            for (String s : fields) {
                Set<ConstraintViolation<T>> constraintViolations = validator.validateProperty(t, s);
                for (Iterator<ConstraintViolation<T>> iter = constraintViolations.iterator(); iter.hasNext(); ) {
                    ConstraintViolation violation = iter.next();
                    buf.append(violation.getMessage() + "<BR>");
                }
            }
            return buf.toString();
        } catch (Exception e) {
        	log.error("error",e);
        }
        return null;
    }

    /**
     * 若是图片，则通过缩放来判断，可以缩放的为图片，不可以的则不是
     * @param file
     * @return
     */
    public static final boolean isImage(File file) {
        boolean flag = false;
        try {
            BufferedImage bufreader = ImageIO.read(file);
            int width = bufreader.getWidth();
            int height = bufreader.getHeight();
            flag = !(width == 0 || height == 0);
        } catch (IOException e) {
        	log.error("error",e);
        } catch (Exception e) {
        	log.error("error",e);
        }
        return flag;
    }
}
